package com.dykj.fireFighting.web.dutymanger;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import com.dykj.fireFighting.api.base.effecttimesetting.service.IEffectiveTimeSettingService;
import com.dykj.fireFighting.api.base.effecttimesetting.vo.EffectiveTimeSettingVo;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.file.service.DataFilesService;
import com.dykj.fireFighting.api.base.file.service.OfficeService;
import com.dykj.fireFighting.api.socialUnit.dutymanger.dto.DutyRecordDto;
import com.dykj.fireFighting.api.socialUnit.dutymanger.entity.DutyRecord;
import com.dykj.fireFighting.api.socialUnit.dutymanger.service.IDutyRecordService;
import com.dykj.fireFighting.api.socialUnit.dutymanger.vo.DutyRecordVo;
import com.dykj.fireFighting.api.socialUnit.unitShift.dto.UnitShiftDto;
import com.dykj.fireFighting.api.socialUnit.unitShift.entity.UnitShift;
import com.dykj.fireFighting.api.socialUnit.unitShift.service.IUnitShiftService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;



/**
 * 值班记录表管理接口
 *
 * @Author zly
 * @Date  2021-07-20 16:48:48
 */
@Slf4j
@Api(value = "值班记录表管理接口", tags = {"值班记录表管理接口"})
@RestController
@RequestMapping("dutymanger/dutyRecord")
public class DutyRecordController {

    @DubboReference
    private IDutyRecordService dutyRecordService;
    @DubboReference
    private OfficeService officeService;
    @DubboReference
    private DataFilesService dataFilesService;
    @DubboReference
    private IUnitShiftService unitShiftService;
    @DubboReference
    private IEffectiveTimeSettingService effectiveTimeSettingService;
    @DubboReference
    private IEnterpriseService enterpriseService;
    /**
     * 值班记录表管理列表
     *
     * @return
     */
    @AutoLog(value = "值班记录表管理-分页列表查询")
    @ApiOperation(value = "值班记录表管理分页列表", notes = "值班记录表管理分页列表")
    @GetMapping("/list")
    //@RequiresPermissions("dutymanger/dutyRecord/list")
    public CommonResult<PageVo<DutyRecord>> treeGrid(DutyRecordDto dutyRecordDto) {
        LoginUserVo user = ShiroUtil.getUser();
        dutyRecordDto.setUnitId(user.getEnterpriseId().toString());
        PageVo<DutyRecord> page = dutyRecordService.queryList(dutyRecordDto);
        return CommonResult.success(page);
    }

    /**
     * 获取值班记录表管理信息
     */
    @AutoLog(value = "值班记录表管理-获取值班记录表管理信息")
    @ApiOperation(value = "获取值班记录表管理信息", notes = "获取值班记录表管理信息")
    @ApiImplicitParam(paramType = "path", name = "code", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{code}")
    //@RequiresPermissions("dutymanger/dutyRecord/info")
    public CommonResult<DutyRecord> info(@PathVariable("code") String code){
        DutyRecordVo dutyRecord = dutyRecordService.getInfo(code);
        return CommonResult.success(dutyRecord);
    }

    /**
     * 保存值班记录表管理信息
     */
    @AutoLog(value = "值班记录表管理-保存值班记录表管理信息")
    @ApiOperation(value = "保存值班记录表管理信息", notes = "保存值班记录表管理信息")
    @PostMapping("/save")
    //@RequiresPermissions("dutymanger/dutyRecord/save")
    public CommonResult save(@Valid @RequestBody DutyRecord dutyRecord) {
        try {
            LoginUserVo user = ShiroUtil.getUser();
            dutyRecord.setCreateDate(new Date());
            dutyRecord.setCode(UUIDUtils.get32UUID());
            dutyRecord.setCreateBy(user.getId().toString());
            dutyRecord.setUnitId(user.getEnterpriseId().toString());

            UnitShiftDto dutyRecordDto=new UnitShiftDto();
            dutyRecordDto.setUnitId(user.getEnterpriseId().toString());
            List<UnitShift> list = unitShiftService.queryList(dutyRecordDto);
            boolean flag=true;
            String shiftId="";
            String dataStr= DateUtil.getNowDateStr();
            LoginUserVo loginUserVo = ShiroUtil.getUser();
            Enterprise enterprise=enterpriseService.getInfoByBindingCode(loginUserVo.getBindingCode());
            for (int i = 0; i < list.size(); i++) {
                String dateTime=dataStr+" "+list.get(i).getEndTime();
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sourceTime=sdf.parse(dateTime);
                EffectiveTimeSettingVo effectiveTimeSettingVo = effectiveTimeSettingService.isEffective(sourceTime, "patrol", enterprise.getId().toString());
                if (effectiveTimeSettingVo.getIsEffective()) {
                    flag=true;
                    shiftId=list.get(i).getId();
                    break;
                } else {
                    flag=false;
                }
            }
            if(flag){
                int count=dutyRecordService.selectCount(loginUserVo.getId().toString(),shiftId,dataStr);
                if(count==0){
                    dutyRecord.setIsQualified(0);
                    dutyRecord.setUnitShiftId(shiftId);
                }else{
                    dutyRecord.setIsQualified(1);
                }
            }else{
                dutyRecord.setIsQualified(1);
            }

            dutyRecordService.save(dutyRecord);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改值班记录表管理信息
     */
    @AutoLog(value = "值班记录表管理-修改值班记录表管理信息")
    @ApiOperation(value = "修改值班记录表管理信息", notes = "修改值班记录表管理信息")
    @PostMapping("/update")
    //@RequiresPermissions("dutymanger/dutyRecord/update")
    public CommonResult update(@Valid @RequestBody DutyRecord dutyRecord) {
        try {

                dutyRecordService.updateById(dutyRecord);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除值班记录表管理信息
     */
    @AutoLog(value = "值班记录表管理-删除值班记录表管理信息")
    @ApiOperation(value = "删除值班记录表管理信息", notes = "删除值班记录表管理信息")
    @ApiImplicitParam(paramType = "query", name = "codes", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
    //@RequiresPermissions("dutymanger/dutyRecord/delete")
    public CommonResult delete(@RequestBody String[]codes) {
        try {
                dutyRecordService.removeByIds(Arrays.asList(codes));
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

   // @AutoLog(value = "值班记录表管理-下载值班记录表管理信息")
   // @ApiOperation(value = "下载值班记录表管理信息", notes = "下载值班记录表管理信息")
    @ApiImplicitParam(paramType = "query", name = "codes", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @GetMapping("/downLoad/{id}")
    public CommonResult downLoad(@PathVariable("id") String id, HttpServletResponse response) throws Exception {

        DutyRecord dutyRecord = dutyRecordService.getById(id);
        if(dutyRecord.equals(1)){
            dutyRecord.setDutyStatusDes("设备报警");
        }else{
            dutyRecord.setDutyStatusDes("设备正常");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("dutyRecord",dutyRecord);
        String s = officeService.saveEXceltoMongo(map,dutyRecord.getPicturePath(),"dutyRecord.xlsx", "值班记录表.xlsx");

         return CommonResult.success(s,"成功");

    }
}
